package com.atguigu.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: shy
 * @Date: 2021/05/21/18:23
 * @Description:
 */
@Service
public class OssServiceImpl implements OssService {

    //上传头像到OSS
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取值
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        InputStream inputStream = null;
        try{
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件的输入流
            inputStream = file.getInputStream();

            //获取文件名称
            String filename = file.getOriginalFilename();
            // 在文件名称里添加唯一随机的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // aewaes12.jpg
            filename = uuid + filename;

            // 文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath + "/" + filename;
            //调用oss实例中的方法实现上传
            //参数1： Bucket名称
            //参数2： 上传到oss文件路径和文件名称 /aa/bb/1.jpg
            //参数3： 上传文件的输入流
            ossClient.putObject(bucketName, filename, inputStream);

            ossClient.shutdown();

            //把上传后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //   https://shan-edu.oss-cn-chengdu.aliyuncs.com/default.gif
            // bucketName  shan-edu  endpoint  oss-cn-chengdu.aliyuncs.com
            String url = "http://"+bucketName+"."+endpoint+"/"+filename ;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
